from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from cmdb.models import IDC,Asset
from cmdb.forms import IDCForm,AssetForm


def idcs(request):
    '''显示IDC'''
    idcs = IDC.objects.all()
    context = {'idcs':idcs}
    return render(request,'cmdb/idcs.html',context)

def idc(request,idc_id):
    '''显示IDC域所有主机'''
    idc = IDC.objects.get(id=idc_id)
    #assets = idc.asset_set.order_by('-date_added')
    assets = idc.asset_set.order_by('-create_at')
    context = {'idc': idc,'assets': assets}
    return render(request,'cmdb/idc.html',context)    


def add_idcs(request):
    '''添加一个新IDC'''
    if request.method != 'POST':
     # 未提交数据：创建一个新表
        form = IDCForm()
    else:
     # POST 提交的数据，对数据进行处理
        form = IDCForm(request.POST)
        if form.is_valid():
            add_idcs = form.save(commit=False)
            add_idcs.owner = request.user
            form.save()
            return HttpResponseRedirect(reverse('cmdb:idcs'))
    context = {'form': form}
    return render(request,'cmdb/add_idcs.html',context)


def add_asset(request,idc_id):
    '''在特定的IDC上添加Asset'''
    idc = IDC.objects.get(id=idc_id)
    if request.method != 'POST':
        form = AssetForm()
    else:
        form = AssetForm(data=request.POST)
        if form.is_valid():
            add_asset = form.save(commit=False)
            add_asset.idc = idc
            add_asset.save()
            return HttpResponseRedirect(reverse('cmdb:idc',args=[idc_id]))
    context = {'idc': idc,'form': form}
    return render(request, 'cmdb/add_asset.html',context)
